package com.test.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class NettyTcpServer implements ApplicationListener<ApplicationStartedEvent> {

    @Value("${netty.port:9001}")
    private int port;
    @Value("${netty.time-out:300}")
    private int timeOut;

    private NioEventLoopGroup boosGroup = new NioEventLoopGroup();
    private NioEventLoopGroup workGroup = new NioEventLoopGroup();

    private Channel channel;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new IdleStateHandler(timeOut, 0, 0 , TimeUnit.SECONDS));
                            pipeline.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("\r\n".getBytes("UTF-8"))));

                            channel = ch;
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

            if(channelFuture.isSuccess()){
                log.info("启动TCP服务完毕, port:{}", port);
            }
        } catch (InterruptedException e) {
            log.error("TCP服务启动失败:{}", e.getMessage());
        }

    }

    @PreDestroy
    public void destory() {
        if (boosGroup != null) {
            boosGroup.shutdownGracefully();
        }

        if (workGroup != null) {
            workGroup.shutdownGracefully();
        }
    }

    public Channel getChannel() {
        return channel;
    }
}
